package com.bilibili.juc.cf.one;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
/*
 * 演示 CompletableFuture 链式调用
 *
 * */
public class CompleteFutureChainCallDemo {
    public static void main(String[] args) throws Exception {
        CompletableFuture.supplyAsync(() -> fetchUserId())
                .thenCompose(userId -> fetchUserDetail(userId)) // 依赖前序结果
                .thenAccept(userDetail -> saveToDB(userDetail));
        System.in.read();
    }

    private static CompletionStage<UserDetail> fetchUserDetail(Long userId) {
        System.out.println("****** CompleteFutureChainCallDemo.fetchUserDetail userId=" + userId + "");
        return CompletableFuture.supplyAsync(() -> {
            UserDetail userDetail = new UserDetail();
            userDetail.setUserId(userId);
            return userDetail;

        });
    }

    private static <U> Long fetchUserId() {
        System.out.println("****** CompleteFutureChainCallDemo.fetchUserId");
        return 219L;
    }

    private static void saveToDB(UserDetail userDetail) {
        System.out.println("****** CompleteFutureChainCallDemo.saveToDB userDetail=" + userDetail + "");

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class UserDetail {
        private Long userId;
    }
}
